package com.example.electricbicycle.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.example.electricbicycle.dao.UserDAO;
import com.example.electricbicycle.dao.UserDAOImpl;
import com.example.electricbicycle.po.User;
import utils.DBUtils;

public class UserServiceImpl implements UserService {
    private final UserDAO userDao = new UserDAOImpl();

    @Override
    public User login(String username, String password) {
        return userDao.findUser(username, password);
    }

    @Override
    public List<User> getAllUsers(int currentPage, int pageSize) {
        System.out.println("[Service] 获取用户列表 - 当前页: " + currentPage + ", 每页大小: " + pageSize);

        // 确保页码有效
        if (currentPage < 1) {
            currentPage = 1;
        }

        List<User> users = userDao.findAllUsers(currentPage, pageSize);
        System.out.println("[Service] 返回用户数量: " + (users != null ? users.size() : 0));
        return users;
    }
    @Override
    public int getUserCount() {
        return userDao.getUserCount();
    }

    @Override
    public User getUserById(int id) {
        return userDao.findUserById(id);
    }

    @Override
    public boolean addUser(User user) {
        // 基础参数校验
        if (user == null || user.getName() == null || user.getPassword() == null) {
            return false;
        }

        // 用户名唯一性检查
        if (userDao.checkUsernameExists(user.getName())) {
            return false;
        }

        return userDao.addUser(user) > 0;
    }

    @Override
    public boolean updateUser(User user) {
        if (user == null || user.getId() == 0) {
            return false;
        }
        return userDao.updateUser(user) > 0;
    }

    @Override
    public boolean deleteUser(int id) {
        return userDao.deleteUser(id) > 0;
    }

    @Override
    public boolean changePassword(int userId, String oldPassword, String newPassword) {
        User user = userDao.findUserById(userId);

        // 验证用户存在性
        if (user == null) {
            return false;
        }

        // 验证原密码
        if (!user.getPassword().equals(oldPassword)) {
            return false;
        }

        // 密码复杂度检查
        if (!isValidPassword(newPassword)) {
            return false;
        }

        user.setPassword(newPassword);
        return updateUser(user);
    }
    private boolean isValidPassword(String password) {
        if (password == null || password.length() < 6) {
            return false;
        }
//        if (password.matches("(.)\\1{5,}")) {
//            return false;
//        }
        return true;
    }

    @Override
    public List<User> getAllUsers() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<User> searchUsers(String keyword, int page, int pageSize) {
        String sql = "SELECT * FROM user WHERE name LIKE ? LIMIT ? OFFSET ?";
        List<User> userList = new ArrayList<>();

        try (Connection conn = DBUtils.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            String searchKey = "%" + keyword + "%";
            pstmt.setString(1, searchKey);
            pstmt.setInt(2, pageSize);
            pstmt.setInt(3, (page - 1) * pageSize);

            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setPassword(rs.getString("pass"));
                user.setRole(rs.getInt("role"));
                userList.add(user);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return userList;
    }

    @Override
    public int getUserCount(String keyword) {
        String sql = "SELECT COUNT(*) FROM t_user";
        String condition = "";
        if (keyword != null && !keyword.trim().isEmpty()) {
            sql += " WHERE v_name LIKE ?";
            condition = "%" + keyword + "%";
        }

        try (Connection conn = DBUtils.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            if (keyword != null && !keyword.trim().isEmpty()) {
                pstmt.setString(1, condition);
            }

            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                return rs.getInt(1);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<User> complexQuery(Map<String, Object> params, int start, int count) {
        List<User> userList = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtils.getConnection();
            StringBuilder sql = new StringBuilder("SELECT id, name, pass, role FROM user WHERE 1=1");

            // 动态构建查询条件
            if (params.containsKey("name")) {
                sql.append(" AND name LIKE ?");
            }
//            if (params.containsKey("role")) {
//                sql.append(" AND role = ?");
//            }
//            sql.append(" LIMIT ?, ?");

            ps = conn.prepareStatement(sql.toString());
            int paramIndex = 1;

            // 设置查询参数
            if (params.containsKey("name")) {
                ps.setString(paramIndex++, "%" + params.get("name") + "%");
            }
//            if (params.containsKey("role")) {
//                ps.setString(paramIndex++, (String) params.get("role"));
//            }

//            // 设置分页参数
//            ps.setInt(paramIndex++, start);
//            ps.setInt(paramIndex, count);

            rs = ps.executeQuery();

            // 处理查询结果
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setPassword(rs.getString("pass"));
                user.setRole(rs.getInt("role"));
                userList.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.close(conn, ps, rs);
        }
        return userList;
    }

    @Override
    public int getTotal(Map<String, Object> params) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int total = 0;

        try {
            conn = DBUtils.getConnection();
            StringBuilder sql = new StringBuilder("SELECT COUNT(*) AS total FROM user WHERE 1=1");

            // 动态构建查询条件
            if (params.containsKey("name")) {
                sql.append(" AND name LIKE ?");
            }
            if (params.containsKey("role")) {
                sql.append(" AND role = ?");
            }

            ps = conn.prepareStatement(sql.toString());
            int paramIndex = 1;

            // 设置查询参数
            if (params.containsKey("name")) {
                ps.setString(paramIndex++, "%" + params.get("name") + "%");
            }
            if (params.containsKey("role")) {
                ps.setString(paramIndex, (String) params.get("role"));
            }

            rs = ps.executeQuery();

            // 获取总数
            if (rs.next()) {
                total = rs.getInt("total");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.close(conn, ps, rs);
        }
        return total;
    }
    public int getAdminCount() {
        return userDao.getUserCountByRole(4);
    }

    public int getSalesCount() {
        return userDao.getUserCountByRole(0);
    }

    public int getWarehouseCount() {
        return userDao.getUserCountByRole(1);
    }

    public int getSalesAdminCount() {
        return userDao.getUserCountByRole(2);
    }

    public int getAfterSalesCount() {
        return userDao.getUserCountByRole(3);
    }
}
